<template>
	<view>
		<view class="big-Active">
			<template v-if="bigActive == 'pusher' ">
				<live-pusher id='livePusher' ref="livePusher" :device-position="position" :autopush="autoplay"
					audio-quality="high" style="height:100%; width: 100%" :url="pushUrl" mode="RTC" max-bitrate="500"
					min-bitrate="200" />
			</template>
			<template v-else>
				<live-player sound-mode="speaker" :autoplay="autoplay" id="player" :src="playUrl" mode="RTC" min-cache="0.1"
					max-cache="0.3" object-fit="fillCrop" style="height:100%; width: 100%;" />
			</template>
		</view>
		<view class="small-active" @click="changeActive">
			<template v-if="bigActive == 'pusher' ">
				<live-player sound-mode="speaker" :autoplay="autoplay" id="player" :src="playUrl" mode="RTC" min-cache="0.1"
					max-cache="0.3" object-fit="fillCrop" style="height:100%; width: 100%;" />
			</template>
			<template v-else>
				<live-pusher id='livePusher' ref="livePusher" :device-position="position" :autopush="autoplay"
					audio-quality="high" style="height:100%; width: 100%" :url="pushUrl" mode="RTC" max-bitrate="500"
					min-bitrate="200" />
			</template>
		</view>
		<view class="call-bottom">
			<view>{{calltime}}</view>
			<view class="call-bottom-btn">
				<view style="display: flex;flex-direction: column;align-items: center;">
					<view
						style="width: 145rpx;height: 145rpx;border-radius: 50%;background-color: #FFFFFF;margin-bottom: 10rpx;">
						<image class="bottom-icon" mode="widthFix" src="../../static/images/hangup.png" @click="hangup">
						</image>
					</view>
					<view>挂断</view>
				</view>
				<view style="display: flex;flex-direction: column;align-items: center;">
					<view
						style="width: 130rpx;height: 130rpx;border-radius: 50%;border:2rpx solid #FFFFFF;margin-bottom: 10rpx;display: flex;align-items: center;justify-content: center;box-sizing: border-box;"
						@click="change">
						<image style="width: 80rpx;" mode="widthFix" src="../../static/images/change.png"></image>
					</view>
					<view>切换摄像头</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const AgoraMiniappSDK = require('../../sdk/Agora_Miniapp_SDK_for_WeChat.js');
	export default {
		components: {},
		data() {
			return {
				flag: null,
				callS:0,
				callM:0,
				callH:0,
				calltime: '00:00:00',
				bigActive: 'player',
				position: 'front',
				autoplay: true,
				playUrl: "",
				pushUrl: "",
				client: undefined,
				from: undefined,
				ctx: undefined
			}
		},
		onReady() {
			// 注意：需要在onReady中 或 onLoad 延时
			this.context = uni.createLivePusherContext("livePusher", this);
		},
		onLoad(option) {
			let ext = JSON.parse(option.ext)
			let from = option.from
			let to = option.toUserId
			this.from = parseInt(from)
			this.func.$request('usr/token/getToken.tz',{channelName: ext.channelName,userAccount: to},'GET').then(item=>{
				
					var that = this;
					let client = new AgoraMiniappSDK.Client();
					this.client = client
					client.init("cbfd2964c3834274be19c452c82f4237",()=>{
						// 初始化成功
						console.log("初始化成功");
						client.join(item.data.result.token, ext.channelName, item.data.result.uid,
							(uid) => {
								// 加入成功
								console.log("加入成功");
								// 发布本地音频流并获取推流 url 地址
								client.publish((res) => {
									// 发布成功
									console.log("发布成功", res);
									that.pushUrl = res
									// 监听
									client.subscribe(parseInt(from),(playres) => {
										console.log("订阅成功", playres);
										that.playUrl = playres
										this.flag = setInterval(()=>{
											this.countCallTime()
										},1000)
									}, function(err) {
										console.log("订阅失败" + err);
									}, {
										audio: true,
										video: true
									})
									client.on('error', function(err) {
										console.log("Got error msg:", err.reason);
										if (err.reason === 'DYNAMIC_KEY_TIMEOUT') {
											client.renewChannelKey(that.data
												.fangjianhao,
												function() {
													console.log(
														"Renew channel key successfully"
														);
												},
												function(err) {
													console.log(
														"Renew channel key failed: ",
														err);
												});
										}
									});
									// 监听远程视频添加
									client.on('stream-added', function(evt) {
										client.subscribe(evt.uid, function(res) {
											console.log("订阅视频流成功playUrl",res);
										}, function(err) {
											console.log("订阅视频流错误", err);
										});
									});
				
									client.on('update-url', function(evt) {
										console.log("视频播放", evt);
									});
				
									client.on('stream-removed', evt => {
										console.log("视频停止播放");
										uni.showToast({
											title: '通话结束',
											duration: 2000
										});
										if (this.client) {
											this.client.unsubscribe(this.from,
												res => {
													console.log("停止订阅成功");
												}, res => {
													console.log("停止订阅失败");
												})
											this.client.unpublish(res => {
												console.log("停止发布成功");
											}, res => {
												console.log("停止发布失败");
											})
											this.client.leave(res => {
												console.log("退出频道成功");
											}, res => {
												console.log("退出频道失败");
											})
											// uni.reLaunch({
											// 	url: "/pages/index/index"
											// });
											uni.navigateBack({
												delta:1
											})
										}
				
									});
				
									client.on('video-rotation', function(evt) {
										console.log(evt.uid," leaved from this channel");
									});
								}, function(err) {
									// 发布失败
									console.log("发布失败" + err);
								});
							},
							function(err) {
								console.log("加入失败", err);
							});
					}, function(err) {
						console.log("初始化失败", err);
					});
			})
		},
		onShow() {},
		methods: {
			countCallTime(){
				if(this.callS == 59){
					if(this.callM == 59){
						this.callH++
						this.callM = 0
					}else{
						this.callM++
					}
					this.callS = 0
				}else{
					this.callS++;
				}
				let s = this.callS >= 10? this.callS.toString():('0'+this.callS.toString())
				let m = this.callM >= 10? this.callM.toString():('0'+this.callM.toString())
				let h = this.callH >= 10? this.callH.toString():('0'+this.callH.toString())
				this.calltime = h+':'+m+':'+s
			},
			changeActive(){
				console.log('===============changeActive')
				this.bigActive = (this.bigActive == 'pusher')?'player':'pusher'
			},
			hangup() {
				if (this.client) {
					this.client.unsubscribe(this.from, res => {
						console.log("停止订阅成功");
					}, res => {
						console.log("停止订阅失败");
					})
					this.client.unpublish(res => {
						console.log("停止发布成功");
					}, res => {
						console.log("停止发布失败");
					})
					this.client.leave(res => {
						console.log("退出频道成功");
					}, res => {
						console.log("退出频道失败");
					})
					// uni.reLaunch({
					// 	url: "/pages/index/index"
					// });
					uni.navigateBack({
						delta:1
					})
				}
			},
			change() {
				// this.position = (this.position == 'front')?'back':'front'
				this.context.switchCamera({
					success: (a) => {
						console.log("livePusher.switchCamera:" + JSON.stringify(a));
					},
				});
			}
		}
	}
</script>

<style scoped>
	.call-bottom {
		position: absolute;
		bottom: 0rpx;
		left: 0rpx;
		width: 100vw;
		height: 30vh;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #FFFFFF;
	}
	.call-bottom-btn{
		width: 100vw;
		display: flex;
		justify-content: space-around;
		align-items: center;
	}
	.bottom-icon {
		width: 145rpx;
	}
	
	.big-Active{
		width: 100%;
		height: 100vh; 
		padding: 0rpx;
	}
	.small-active{
		width: 200rpx; 
		height: 200rpx; 
		padding: 0rpx;
		position: absolute;
		top: 10rpx;
		right: 10rpx;
	}
</style>
